<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 栅格布局 -->
      <el-row :gutter="20">
        <!-- 第一列 -->
        <el-col :span="8">
          <!-- 搜索栏 -->
          <el-input
            placeholder="请输入内容"
            v-model="queryData.query"
            @keyup.native.enter="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 第二列 -->
        <el-col :span="4">
          <el-button type="primary" @click="isShow = true">用户新增</el-button>
        </el-col>
      </el-row>

      <!-- 表格区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="username" label="姓名"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <template slot-scope="ele">
            <el-switch
              @change="changeState(ele.row)"
              v-model="ele.row.mg_state"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150px">
          <template slot-scope="ele">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="changeUser(ele.row)"
              circle
            ></el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deleteUser(ele.row)"
              circle
            ></el-button>
            <el-tooltip content="设置权限" placement="top" :enterable="false">
              <el-button
                type="warning"
                size="mini"
                icon="el-icon-setting"
                circle
                @click="showSetRoleDialog(ele.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页码条 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryData.pagenum"
        :page-sizes="[1, 2, 3, 4, 5, 8]"
        :page-size="queryData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="isShow"
        width="30%"
        :before-close="handleClose"
        @close="closeDialog"
      >
        <!-- 新增表单 -->
        <el-form
          ref="addFormRef"
          :model="addFormData"
          label-width="80px"
          :rules="addRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="addFormData.username"
              @keyup.native.enter="addUser"
            ></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="addFormData.password"
              @keyup.native.enter="addUser"
            ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="addFormData.email"
              @keyup.native.enter="addUser"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="mobile">
            <el-input
              v-model="addFormData.mobile"
              @keyup.native.enter="addUser"
            ></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="isShow = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户对话框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="changeUserShow"
        width="30%"
        :before-close="handleClose"
        @close="closeEditDialog"
      >
        <el-form
          ref="editFormRef"
          :model="editForm"
          label-width="80px"
          :rules="editFormRules"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="changeUserShow = false">取 消</el-button>
          <el-button type="primary" @click="editUser()">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色对话框 -->
      <el-dialog
        title="分配角色"
        :visible.sync="setRoleDialogVisible"
        width="50%"
        :before-close="handleClose"
      >
        <div>
          <p>当前用户:{{ currentUser.username }}</p>
          <p>当前角色:{{ currentUser.role_name }}</p>
          <p>
            <el-select v-model="selectRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRole()">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data: function () {
    // 手机号校验规则
    const mobleRuleCheck = (rule, value, cb) => {
      const p = /^1[3|5|7|8|9]\d{9}$/
      if (p.test(value)) return cb()
      cb(new Error('请输入合法手机号'))
    }
    return {
      // 用户列表查询参数对象
      queryData: {
        query: '', // 查询参数
        pagenum: 1, // 当前页码
        pagesize: 4 // 页容量
      },
      userList: [], // 用户数组
      total: 0, // 总用户数
      isShow: false, // 是否显示添加用户对话框
      changeUserShow: false, // 是否显示修改用户对话框
      setRoleDialogVisible: false, // 是否显示分配角色对话框
      addFormData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: mobleRuleCheck, trigger: 'blur' }
          // { pattern: /^1[3|5|7|8|9]\d{9}$/, message: '手机格式不合法~', trigger: 'blur' }
        ]
      },

      // 修改用户对象
      editForm: {},
      // 修改用户对象规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机', trigger: 'blur' },
          { validator: mobleRuleCheck, trigger: 'blur' }
        ]
      },

      // 分配角色
      currentUser: {}, // 当前的用户
      roleList: [], // 角色列表
      selectRoleId: ''// 选中的角色id
    }
  },
  methods: {
    // 异步请求 用户列表
    async getUserList () {
      // 发送异步请求，并解构返回对象中的data属性，赋值给resBody
      const { data: resBody } = await this.$http.get('users', {
        params: this.queryData
      })
      // 如果失败，则返回错误消息，并退出函数执行
      if (resBody.meta.status !== 200) return this.$msg.error(resBody.meta.msg)
      // 如果成功，则将返回的数据赋值给data，重绘视图
      this.userList = resBody.data.users
      this.total = resBody.data.total
    },

    // 设置页容量函数
    handleSizeChange (newPageSize) {
      // 将新的页码条容量，赋值给Data
      this.queryData.pagesize = newPageSize
      // 重新发送异步请求，获取当前页数据
      this.getUserList()
    },

    // 设置页码函数
    handleCurrentChange (newPageIndex) {
      // 将被点击的页码，赋值给Data
      this.queryData.pagenum = newPageIndex
      // 重新发送异步请求，获取当前页数据
      this.getUserList()
    },

    // 状态改变事件
    async changeState (rowData) {
      const { data: resBody } = await this.$axios.put(
        `users/${rowData.id}/state/${rowData.mg_state}`
      )
      // 如果请求失败，则返回错误消息，并结束函数执行
      if (resBody.meta.status !== 200) {
        rowData.mg_state = !rowData.mg_state
        return this.$msg.error(resBody.meta.msg)
      }
      // 如果成功
      this.$msg.success(resBody.meta.msg)
      // this.
    },

    // 关闭对话框
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then((_) => {
          done()
        })
        .catch((_) => {})
    },

    // 关闭对话框事件后重置
    closeDialog () {
      this.$refs.addFormRef.resetFields()
    },

    // 添加新用户
    addUser () {
      // 发送请求前预校验
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: resBody } = await this.$axios.post(
          'users',
          this.addFormData
        )
        // 如果请求失败，则返回错误信息，并结束函数执行
        if (resBody.meta.status !== 201) {
          return this.$msg.error(resBody.meta.msg)
        }
        // 如果成功
        this.getUserList()
        this.isShow = false
        this.$msg.success(resBody.meta.msg)
      })
    },

    // 删除新用户
    deleteUser (userId) {
      // 确认是否删除，通过elmecon
      this.$confirm('是否确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async action => {
        const { data: resBody } = await this.$axios.delete(`users/${userId.id}`)
        // 如果请求失败，则返回错误信息，并结束函数执行
        if (resBody.meta.status !== 200) return this.$msg.error(resBody.meta.msg)
        // 如果成功
        this.$msg.success(resBody.meta.msg)
        this.getUserList()
      }).catch(() => {

      })
    },

    // 修改用户信息
    async changeUser (userId) {
      // 是否打开修改用户对话框
      this.changeUserShow = true
      // 根据 ID 查询用户信息
      const { data: resBody } = await this.$axios.get(`users/${userId.id}`)
      // 如果请求失败，则返回错误信息，并结束函数执行
      if (resBody.meta.status !== 200) return this.$msg.error(resBody.meta.msg)
      // 如果请求成功，则提示正确信息
      this.$msg.success(resBody.meta.msg)
      // 将获得的数据渲染到对话框里
      this.editForm = resBody.data
    },

    // 关闭修改用户对话框后重置
    closeEditDialog () {
      this.$refs.editFormRef.resetFields()
    },

    // 上传修改后的用户信息
    editUser (userId) {
      // 修改前的预校验
      this.$refs.editFormRef.validate(async (isOk) => {
        if (!isOk) return
        const { data: resBody } = await this.$axios.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        // 验证是否成功修改
        if (resBody.meta.status !== 200) {
          // 如果失败，返回错误信息
          return this.$message({
            message: '编辑失败',
            type: 'error',
            showClose: true,
            duration: 3000
          })
        }
        // // 成功提示
        // this.$message({
        //   message: '编辑成功',
        //   type: 'success',
        //   showClose: true,
        //   duration: 3000
        // })
        // 关闭对话框
        this.changeUserShow = false
        // 刷新列表
        this.getUserList()
      })
    },

    // 分配角色
    async showSetRoleDialog (row) {
      this.currentUser = row
      this.setRoleDialogVisible = true
      const { data: res } = await this.$http.get('roles')
      this.roleList = res.data
    },

    // 分配用户角色
    async setRole () {
      console.log(this.currentUser.id)
      console.log(this.selectRoleId)
      await this.$axios.put(`users/${this.currentUser.id}/role`, { rid: this.selectRoleId })
      // 成功提示
      this.$message({
        message: '编辑成功',
        type: 'success',
        showClose: true,
        duration: 3000
      })
      // 关闭对话框
      this.setRoleDialogVisible = false
      // 刷新列表
      this.getUserList()
    }
  },
  // 钩子函数
  created () {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
</style>
